package cc.messcat.service.log;

import cc.messcat.common.model.Pager;
import cc.messcat.common.service.BaseServiceImpl;
import cc.messcat.dao.log.LogDao;
import cc.messcat.entity.log.Log;
import cc.messcat.entity.system.McUser;
import cc.messcat.util.ExcelUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LogServiceImpl extends BaseServiceImpl<Log> implements LogService {
    static Logger logger = LoggerFactory.getLogger("工作圈");
	@Autowired
	private LogDao logDao;

	@Override
	public void addlog(Log log) {

		addObject(log);
	}

	@Override
	public Pager<Log> getPagerfindAllList(int pageNo, int pageSize) {
		Map map = new HashMap<>();
		String hql = "from Log ORDER BY add_time DESC";
		return this.logDao.getPagerByHql(pageNo, pageSize, hql, map);
	}

	/**
	 * 日志条件查询
	 * 
	 * @author Fog
	 */
	@Override
	@SuppressWarnings("all")
	public Pager<Log> listLog(McUser user, Integer pageNo, Integer pageSize, Log log, String start, String end) {

		pageNo = pageNo == null || pageNo < 1 ? 1 : pageNo;
		pageSize = pageSize == null || pageSize < 1 ? 12 : pageSize;
		Map condition = new HashMap<>();

		StringBuilder hql = new StringBuilder(" from Log where 1=1 ");

        if(StringUtils.isNotBlank(start)) hql.append(" and add_time >= '" + start + "'");
        if(StringUtils.isNotBlank(end)) hql.append(" and add_time <= '" + end + "'");

        if(StringUtils.isNotBlank(log.getUserName())) hql.append(" and user_name like '%" + log.getUserName() + "%'");
        if(StringUtils.isNotBlank(log.getDescription())) hql.append(" and description like '%" + log.getDescription() + "%'");

        if(StringUtils.isNotBlank(log.getRequestIp())) hql.append(" and request_ip like '%" + log.getRequestIp() + "%'");

        hql.append(" order by add_time desc");
		return logDao.getPagerByHql(pageNo, pageSize, hql.toString(), condition);
	}

	/**
	 * 日志条件删除
	 * @author Fog
	 */
	@Override
	@SuppressWarnings("all")
	public void removeLog(McUser user, Log log,String ids, Date start, Date end) {
		//id批量删除
		Map condition = new HashMap<>();
		if(StringUtils.isNotBlank(ids)) {
			try {
				String[] idss = ids.split(",");
				Long[] idArray = new Long[idss.length];
				for(int i = 0;i<idss.length;i++) {
					idArray[i] = Long.parseLong(idss[i]);
				}
				condition.put("ids", idArray);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				return ;
			}
			logDao.removeLog("delete from Log where id in( :ids )",condition);
			return ;
		}
		
		String hql = "delete from Log where add_time between :start and :end "
			+ " and user_name like :userName and description like :description and request_ip like :ip "
			+ (log != null && log.getId() != null && log.getId() > 0 ? " and id=" + log.getId() : "");

		condition.put("start", start);
		condition.put("end", end);
		condition.put("userName", log != null && StringUtils.isNotBlank(log.getUserName()) ? "%" + log.getUserName() + "%" : "%");
		condition.put("description", log != null && StringUtils.isNotBlank(log.getDescription()) ? "%" + log.getDescription() + "%" : "%");
		condition.put("ip", log != null && StringUtils.isNotBlank(log.getRequestIp()) ? "%" + log.getRequestIp() + "%" : "%");

		logDao.removeLog(hql, condition);
	}

	/**
	 * 日志条件导出
	 * @author Fog
	 */
	@Override
	public HSSFWorkbook exportLog(McUser user, Integer pageNo, Integer pageSize, Log log, String start, String end) {
		String[] cellName = new String[] { "序号", "操作时间", "操作员", "模块", "操作描述", "IP地址", "日志类型" };
		String[] field = new String[] { "addTime", "userName", "method", "description", "requestIp", "type" };
		Integer sheetCount = 0;
		Pager pager = null;
		Map<Integer, List> excelResult = new HashMap<>();

		do {
			sheetCount++;
			pager = listLog(user, sheetCount, 5000, log, start, end);
			excelResult.put(sheetCount, pager.getResultList());

		} while (sheetCount < (pager.getRowCount() + 4999) / 5000);

		HSSFWorkbook workbook = new HSSFWorkbook();
		for (int i = 1; i <= excelResult.size(); i++) {
			HSSFSheet sheet = workbook.createSheet("日志记录表" + i);
			sheet.setDefaultColumnWidth(18);

			HSSFCellStyle headStyle = ExcelUtil.getTitleStyle(workbook);
			HSSFCellStyle cellStyle = ExcelUtil.getCellStyle(workbook);
			HSSFCellStyle columnTitleStyle = ExcelUtil.getColumnTitleStyle(workbook);
			ExcelUtil.addTitle(sheet, cellName, "日志记录表", headStyle, columnTitleStyle);
			ExcelUtil.addContextByList(sheet, excelResult.get(i), field, cellStyle, true);
		}

		return workbook;

	}
	
	/**
	 * 获取备份日志
	 * @param origin
	 * @param derivation
	 * @return
	 */
	@Override
	@SuppressWarnings("unchecked")
	@Deprecated
	public List<Log> getBackupInfo(Integer origin, Integer derivation) {
		return logDao.queryList("from Log where method='备份'",null);
	}

}
